package com.cqh.servlet;

import com.cqh.bean.Student;
import com.cqh.service.StudentService;
import com.cqh.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/Educational/student/getStudentList")
public class GetStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        //1.1模糊查询
        String stuname = req.getParameter("stuname");
        String stuno = req.getParameter("stuno");
        String sex = req.getParameter("sex");
        //1.2分页数据   limit 开始位置，显示条数
        String pageIndex = req.getParameter("pageIndex");
        //  如果没有传入pageIndex的值，则默认为查询第一页
        int index = pageIndex==null?1:Integer.parseInt(pageIndex);
        String pageSize = req.getParameter("pageSize");

        //2.调取service方法
        StudentService studentService = new StudentServiceImpl();
        int pagesize = 5;   //pagesize = Integer.parseInt(pageSize)
        int Sex = sex==null?-1:Integer.parseInt(sex);
        List<Student> studentList = studentService.getAllStudents(stuname,stuno,Sex,index,pagesize);
        //  获取总页数 = 总条数%每页显示的条数>0?总条数/每页条数+1:总条数/每页显示条数
        int total = studentService.total(stuname,stuno,sex==null?-1:Integer.parseInt(sex)); //总条数
        int totalPages = total%pagesize>0?total/pagesize+1:total/pagesize;  //总页数


        //3.跳转页面
        //如果后台给前台传递数据，是一定要在后台进行存值
        req.setAttribute("stulist",studentList);
        //存储模糊查询的条件
        req.setAttribute("stuname",stuname);
        req.setAttribute("stuno",stuno);
        req.setAttribute("sex",Sex);
        //存储分页数据
        req.setAttribute("pageIndex",index);
//        req.setAttribute("pageSize",pagesize);
        req.setAttribute("pageSize",5);
        req.setAttribute("total",total);
        req.setAttribute("totalPages",totalPages);
        req.getRequestDispatcher("list.jsp").forward(req,resp);
    }
}
